package com.example.sdsave;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class MainActivity extends AppCompatActivity {

    private EditText edit_write,edit_read;
    private CheckBox ch_append;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        findViewById(R.id.btn_write).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                write(edit_write.getText().toString());
            }
        });

        findViewById(R.id.btn_read).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_read.setText(read());
            }
        });
    }

    void initView(){
        edit_read=findViewById(R.id.edit_read);
        edit_write=findViewById(R.id.edit_write);
        ch_append=findViewById(R.id.ch_append);
    }

    void write(String content){
        FileOutputStream fileOutputStream=null;
        try {
            if(ch_append.isChecked()){
                fileOutputStream=openFileOutput("file.txt",MODE_APPEND);
            }else {
                fileOutputStream=openFileOutput("file.txt",MODE_PRIVATE);
            }
            PrintWriter printWriter=new PrintWriter(fileOutputStream);
            printWriter.print(content);
            printWriter.close();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String read(){
        StringBuffer content=new StringBuffer();
        try {
            FileInputStream fileInputStream=openFileInput("file.txt");
            byte[] buff=new byte[1024];
            int len=0;
            while ((len=fileInputStream.read(buff))!=-1){
                content.append(new String(buff,0,len));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}
